const serviceMoment = require('../service/moment');
const fs = require("fs");
const path = require("path");
const {PICTURE_PATH} = require('../const/filePath');
class MomentController {
  async createMoment(ctx, next) {
    //获取参数
    const userId = ctx.user.id
    let {content} = ctx.request.body;
    //查询用户是否存在
    const moment = await serviceMoment.createMoment(userId, content);
    ctx.response.body = {
      code: 200,
      userId,
      content,
      moment
    }
  }
  async getMomentDetails(ctx, next) {
    console.log("getMomentDetails中间件")
    //获取参数
    let {momentId,} = ctx.params;
    //查询数据库
    let res = await  serviceMoment.getMomentDetails(momentId);
    //返回结果
    ctx.response.body = {
      code: 200,
      momentId,
      res,
    }
  }
  async getMomentList(ctx, next){
    //
    let{offset,size} = ctx.query; //获取参数
    console.log(offset,size)
    const res = await serviceMoment.getMomentList(offset,size);
    ctx.response.body = {
      code: 200,
      res,
    }
  }
  async updateMoment(ctx, next) {
    //获取参数
    let {momentId,} = ctx.params;
    let {content,} = ctx.request.body;
    //查询数据库
    let res = await  serviceMoment.updateMoment(momentId,content);
    //返回结果
    ctx.response.body = {
      code: 200,
      momentId,
      res,
    }
  }
  async deleteMoment(ctx, next) {
    //获取参数
    let {momentId,} = ctx.params;
    //查询数据库
    let res = await  serviceMoment.deleteMoment(momentId);
    //返回结果
    ctx.response.body = {
      code: 200,
      momentId,
      res,
    }
  }
  async getFileInfoByfilename(ctx,next){
    let {filename} = ctx.params;
    let file = await serviceMoment.getFileInfoByfilename(filename);
    //控制图片大小
    const type =ctx.request.query.type;
    const types = ['small','middle','large'];
    if(types.some(item=>item===type)){
      filename = filename + '-' + type;
    }
    ctx.response.set('content-type',file.mimetype );
    ctx.response.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`);
  }
}
module.exports = new MomentController();